package com.cbgolf.oa.fragment;

import static com.cbgolf.oa.util.AnimaUtil.stopLoading;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cbgolf.oa.R;
import com.cbgolf.oa.activity.coupon.CouponCreateSuccessActivity;
import com.cbgolf.oa.adapter.CouponAdapter;
import com.cbgolf.oa.entity.CouponBean;
import com.cbgolf.oa.entity.NetResponse;
import com.cbgolf.oa.inteface.INetCallBack;
import com.cbgolf.oa.net.NetCallBack;
import com.cbgolf.oa.net.NetUtils;
import com.cbgolf.oa.net.Web;
import com.cbgolf.oa.net.WebAPI;
import com.cbgolf.oa.user.UserData;
import com.cbgolf.oa.util.AnimaUtil;
import com.cbgolf.oa.util.DialogUtil;
import com.cbgolf.oa.util.Util;
import com.cbgolf.oa.widget.autolayout.utils.AutoUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lq on 2017/9/4.
 */

public class CouponFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener,
    CouponAdapter.onCouponClickListener {

  public final static String TAG = "F_Coupon";

  //views
  private View view;
  private SwipeRefreshLayout refreshLayout;
  private ListView listView;
  private TextView loadingTv;
  private View errorView;
  private TextView errorTv;
  private TextView reLoadTv;


  //var
  private String status = "";

  private boolean isLoading;

  private int pageSize = 15;
  private int page = 0;

  private List<CouponBean> listData = new ArrayList<>();
  private CouponAdapter adapter;
  private Handler handler = new Handler();

  public static CouponFragment newInstance(String type) {
    CouponFragment f_coupon = new CouponFragment();
    Bundle b = new Bundle();
    b.putString(TAG, type);
    f_coupon.setArguments(b);
    return f_coupon;
  }

  @Override
  public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (null != getArguments()) {
      status = getArguments().getString(TAG);
    }
    view = getActivity().getLayoutInflater().inflate(R.layout.f_permission_history, null);
    init();
    AutoUtil.auto(view);
  }

  @Nullable
  @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      Bundle savedInstanceState) {
    if (null == view) {
      view = inflater.inflate(R.layout.f_permission_history, null);
      init();
      AutoUtil.auto(view);
    }
    return view;
  }

  @Override
  public void onResume() {
    super.onResume();
  }

  private void init() {
    findViews();
    setViews();
    setListener();
  }

  private void setListener() {
    refreshLayout.setOnRefreshListener(this);
    reLoadTv.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        getData();
      }
    });
    listView.setOnScrollListener(new AbsListView.OnScrollListener() {
      @Override
      public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (listView.getAdapter() != null && listView.getLastVisiblePosition() == (
            listView.getAdapter().getCount() - 1)
            && scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
          if (!isLoading) {
            page++;
            loadMore();
          }
        }
      }

      @Override
      public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
          int totalItemCount) {

      }
    });
    reLoadTv.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        getData();
      }
    });
  }


  private void findViews() {
    refreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.f_permission_swiperRefreshlayout);
    listView = (ListView) view.findViewById(R.id.f_permission_listview);
    errorView = view.findViewById(R.id.g_error_ll);
    errorTv = (TextView) view.findViewById(R.id.g_error_tv);
    reLoadTv = (TextView) view.findViewById(R.id.g_error_reload_tv);
    loadingTv = (TextView) view.findViewById(R.id.g_error_loading_tv);

  }

  private void setViews() {
    adapter = new CouponAdapter(getActivity(), this);
    listView.setAdapter(adapter);
    // 设置下拉圆圈上的颜色，蓝色、绿色、橙色、红色
    refreshLayout.setColorSchemeResources(R.color.bg_blue, R.color.text_gray,
        R.color.white, R.color.bg_blue);
//        refreshLayout.setColorSchemeResources(android.R.color.holo_blue_light,
//                android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light);
    refreshLayout.setDistanceToTriggerSync(300);// 设置手指在屏幕下拉多少距离会触发下拉刷新
    refreshLayout.setSize(SwipeRefreshLayout.LARGE);
    refreshLayout.setProgressBackgroundColorSchemeColor(
        ContextCompat.getColor(getActivity(), R.color.white));
//        refreshLayout.setPageCount(pageSize);

  }

  private void getData() {
    isLoading = true;
    if (!Util.isNetWorkConnected()) {
      showError(NONET);
      return;
    }
    String url = WebAPI.coupons_select_get;
    Map<String, String> map = new HashMap<>();
    map.put("generated", status);
    map.put("pageSize", pageSize + "");
    map.put("currentPage", "0");
    String token = null == UserData.getUser() ? "" : UserData.getUser().getToken();
    map.put("token", token);
    showLoading();
    Web.getOK(url, map, new NetCallBack(new INetCallBack() {
      @Override
      public void onResponse(NetResponse response) {
        if (200 != response.statusCode) {
          showError(NETERROR);
          return;
        }
        if (Util.isNull(response.result)) {
          showError(NODATA);
          return;
        }
        List<CouponBean> list = null;
        try {
          JSONObject json = JSON.parseObject(response.result);
          list = JSON.parseArray(json.getString("content"), CouponBean.class);
        } catch (Exception e) {
          Log.e("catch-------", e.toString());
          showError(NETERROR);
          return;
        }
        if (null != list && list.size() > 0) {
          showData();
          listData.clear();
          listData.addAll(list);
          adapter.setList(listData);
          adapter.upDataUI();
        } else {
          showError(NODATA);
        }
      }

    }));
  }

  private void showLoading() {
    if ((null != refreshLayout && !refreshLayout.isRefreshing()) || listData.size() == 0) {
      AnimaUtil.showLoading(getActivity(), loadingTv);
    }

  }

  private void loadMore() {
    isLoading = true;
    if (!Util.isNetWorkConnected()) {
      showError(LOADMORE);
      return;
    }
    String url = WebAPI.permission_history_get;
    Map<String, String> map = new HashMap<>();
    map.put("generated", status);
    map.put("pageSize", pageSize + "");
    map.put("currentPage", page + "");
    String token = "";
    if (null != UserData.getUser()) {
      token = UserData.getUser().getToken();
    }
    map.put("token", token);
    Web.getOK(url, map, new NetCallBack(new INetCallBack() {
      @Override
      public void onResponse(NetResponse response) {
        if (200 != response.statusCode) {
          showError(LOADMORE);
          return;
        }
        if (Util.isNull(response.result)) {
          showError(LOADMORE);
          return;
        }
        List<CouponBean> list = null;
        try {
          JSONObject json = JSON.parseObject(response.result);
          list = JSON.parseArray(json.getString("content"), CouponBean.class);
        } catch (Exception e) {
          showError(LOADMORE);
          return;
        }
        if (null != list && list.size() > 0) {
          showData();
          listData.addAll(list);
          adapter.upDataUI();
        } else {
          showError(LOADMORE);
        }
      }
    }));
  }

  private void showData() {
    stopLoading();
    if (null != refreshLayout) {
      refreshLayout.setRefreshing(false);
    }
    isLoading = false;
    refreshLayout.setVisibility(View.VISIBLE);
    errorView.setVisibility(View.GONE);
    loadingTv.setVisibility(View.GONE);
  }

  private final int NONET = 1;
  private final int NETERROR = 2;
  private final int NODATA = 3;
  private final int LOADMORE = 4;


  private void showError(int type) {
    stopLoading();
    loadingTv.setVisibility(View.GONE);
    if (null != refreshLayout) {
      refreshLayout.setRefreshing(false);
    }
    isLoading = false;
    if (type == LOADMORE && page > 0) {
      page--;
    }
    if (listData.size() > 0) {
      return;
    }
    if (null != refreshLayout) {
      refreshLayout.setVisibility(View.GONE);
    }
    if (null != errorView) {
      errorView.setVisibility(View.VISIBLE);
    }
    if (null != reLoadTv) {
      reLoadTv.setVisibility(View.VISIBLE);
    }
    if (null == errorTv) {
      return;
    }
    switch (type) {
      case NONET:
        errorTv.setText(getResources().getString(R.string.no_net));
        break;
      case NETERROR:
        errorTv.setText(getResources().getString(R.string.net_error));
        break;
      case NODATA:
        errorTv.setText(getResources().getString(R.string.no_data));
        break;
      default:
        break;
    }


  }

  @Override
  public void onRefresh() {
    if (!isLoading) {
      handler.postDelayed(new Runnable() {
        @Override
        public void run() {
          getData();

        }
      }, 200);
    } else {
      if (null != refreshLayout) {
        refreshLayout.setRefreshing(false);
      }
    }
  }

  @Override
  public void onDel(final int position) {
    String title = "删除提示";
    String msg = "您是否确认删除该券?";
    DialogUtil.showMsgDialog(getActivity(), title, msg, () -> delOrDisableCoupon(position, DEL));
  }


  @Override
  public void onPush(int position) {
    Intent intent = new Intent(getActivity(), CouponCreateSuccessActivity.class);
    String start = "";
    String end = "";
    if (null != listData.get(position).availabilityPeriod) {
      start = listData.get(position).availabilityPeriod.start;
      end = listData.get(position).availabilityPeriod.end;
    }
    try {
      intent.putExtra("startTime", Long.parseLong(start));
      intent.putExtra("overTime", Long.parseLong(end));
    } catch (Exception e) {
    }
    intent.putExtra("moneyNum", String.valueOf(listData.get(position).parValue));
    intent.putExtra("moneyLimit", String.valueOf(listData.get(position).lowestConsumption));
    intent.putExtra("pushCount", String.valueOf(listData.get(position).quantity));
    intent.putExtra("limitCount", String.valueOf(listData.get(position).limitPerOneQuantity));
    intent.putExtra("id", listData.get(position).id);
    intent.putExtra("isCreate", false);
    getActivity().startActivity(intent);
    getActivity().overridePendingTransition(R.anim.in_from_right, R.anim.out_from_left);
  }

  @Override
  public void onDisable(final int position) {
    String title = "确认提示";
    String msg = "您是否选择禁用该券?";
    DialogUtil.showMsgDialog(getActivity(), title, msg, () -> delOrDisableCoupon(position, DISABLE));
  }

  private final int DEL = 1;
  private final int DISABLE = 2;

  private void delOrDisableCoupon(final int position, final int type) {
    if (!Util.isNetWorkConnected()) {
      Util.showNoNet();
      return;
    }
    String id = listData.get(position).id;
    if (Util.isNull(id)) {
      Util.showNetError();
      return;
    }
    String url = WebAPI.coupons_disable_delete + "/" + id + "/receivable";
    if (type == DEL) {
      url = WebAPI.coupons_del_delete + "/" + id;
    }
    AnimaUtil.showLoading(getActivity());
    Web.deleteOk(url, new NetCallBack(response -> {
      stopLoading();
      if (NetUtils.NO_PERMISSION == response.statusCode) {
        Util.show("很抱歉，您没有相关权限");
        return;
      }
      if (NetUtils.SUCCESS != response.statusCode) {
        Util.showNetError();
        return;
      }
      if (type == DISABLE) {
        onRefresh();
      } else {
        Util.show("删除成功");
        listData.remove(position);
        adapter.upDataUI();
      }
    }));
  }
}
